<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联的设备ID" prop="equipmentId">
        <el-input
          v-model="queryParams.equipmentId"
          placeholder="请输入关联的设备ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务类型" prop="taskType">
        <el-input
            v-model="queryParams.taskType"
            placeholder="请输入任务类型"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务优先级" prop="priority">
        <el-input
          v-model="queryParams.priority"
          placeholder="请输入任务优先级"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="问题报告人ID" prop="reportedBy">
        <el-input
          v-model="queryParams.reportedBy"
          placeholder="请输入问题报告人ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="问题上报时间" prop="reportedTime">
        <el-date-picker clearable
          v-model="queryParams.reportedTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择问题上报时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="任务分配的人员ID" prop="assignedToUserId">
        <el-input
          v-model="queryParams.assignedToUserId"
          placeholder="请输入任务分配的人员ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="实际开始处理时间" prop="actualStartTime">
        <el-date-picker clearable
          v-model="queryParams.actualStartTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择实际开始处理时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="实际完成时间" prop="actualEndTime">
        <el-date-picker clearable
          v-model="queryParams.actualEndTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择实际完成时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="实际耗时" prop="actualDurationHours">
        <el-input
          v-model="queryParams.actualDurationHours"
          placeholder="请输入实际耗时"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="任务创建时间" prop="createdAt">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.createdAt"-->
<!--          type="date"-->
<!--          value-format="YYYY-MM-DD"-->
<!--          placeholder="请选择任务创建时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
      <el-form-item label="最后更新时间" prop="updatedAt">
        <el-date-picker clearable
          v-model="queryParams.updatedAt"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择最后更新时间">
        </el-date-picker>


      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['equipment-service:tasks:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['equipment-service:tasks:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['equipment-service:tasks:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['equipment-service:tasks:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tasksList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务ID" align="center" prop="taskId" />
      <el-table-column label="关联的设备ID" align="center" prop="equipmentId" />
      <el-table-column label="任务类型" align="center" prop="taskType" />
      <el-table-column label="问题现象详细描述" align="center" prop="problemDescription" />
      <el-table-column label="解决方案执行记录" align="center" prop="solutionDescription" />
      <el-table-column label="任务状态" align="center" prop="taskStatus" />
      <el-table-column label="任务优先级" align="center" prop="priority" />
      <el-table-column label="问题报告人ID" align="center" prop="reportedBy" />
      <el-table-column label="问题上报时间" align="center" prop="reportedTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reportedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务分配的人员ID" align="center" prop="assignedToUserId" />
      <el-table-column label="实际开始处理时间" align="center" prop="actualStartTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.actualStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际完成时间" align="center" prop="actualEndTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.actualEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际耗时(小时)" align="center">
        <template #default="scope">
          <span>{{ calculateDuration(scope.row.actualStartTime, scope.row.actualEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维护过程补充说明" align="center" prop="notes" />
<!--      <el-table-column label="任务创建时间" align="center" prop="createdAt" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="最后更新时间" align="center" prop="updatedAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              v-if="scope.row.taskStatus !== '已完成'"
              type="primary"
              @click="handleComplete(scope.row)"
              style="background-color: #409EFF; color: white"
          >
            完成
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['equipment-service:tasks:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['equipment-service:tasks:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备维护任务跟踪（记录维护工单全生命周期）对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="tasksRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联的设备ID" prop="equipmentId">
          <el-input v-model="form.equipmentId" placeholder="请输入关联的设备ID" />
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <el-input v-model="form.taskType" placeholder="请输入任务类型"
          />
        </el-form-item>
        <el-form-item label="问题现象详细描述" prop="problemDescription">
          <el-input v-model="form.problemDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="解决方案执行记录" prop="solutionDescription">
          <el-input v-model="form.solutionDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="任务状态" prop="taskStatus">
          <el-select v-model="form.taskStatus" placeholder="请选择任务状态">
            <el-option label="未完成" value="未完成"/>
            <el-option label="已完成" value="已完成"/>
          </el-select>
        </el-form-item>
        <el-form-item label="任务优先级" prop="priority">
          <el-input v-model="form.priority" placeholder="请输入任务优先级" />
        </el-form-item>
        <el-form-item label="问题报告人ID" prop="reportedBy">
          <el-input v-model="form.reportedBy" placeholder="请输入问题报告人ID" />
        </el-form-item>
        <el-form-item label="问题上报时间" prop="reportedTime">
          <el-date-picker clearable
            v-model="form.reportedTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择问题上报时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="任务分配的人员ID" prop="assignedToUserId">
          <el-input v-model="form.assignedToUserId" placeholder="请输入任务分配的人员ID" />
        </el-form-item>
        <el-form-item label="实际开始处理时间" prop="actualStartTime">
          <el-date-picker clearable
            v-model="form.actualStartTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择实际开始处理时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际完成时间" prop="actualEndTime">
          <el-date-picker clearable
            v-model="form.actualEndTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择实际完成时间">
          </el-date-picker>
        </el-form-item>
<!--        <el-form-item label="实际耗时" prop="actualDurationHours">-->
<!--          <el-input v-model="form.actualDurationHours" placeholder="请输入实际耗时" />-->
<!--        </el-form-item>-->
        <el-form-item label="维护过程补充说明" prop="notes">
          <el-input v-model="form.notes" type="textarea" placeholder="请输入内容" />
        </el-form-item>
<!--        <el-form-item label="任务创建时间" prop="createdAt">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.createdAt"-->
<!--            type="date"-->
<!--            value-format="YYYY-MM-DD"-->
<!--            placeholder="请选择任务创建时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
        <el-form-item label="最后更新时间" prop="updatedAt">
          <el-date-picker clearable
            v-model="form.updatedAt"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择最后更新时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tasks">
import { listTasks, getTasks, delTasks, addTasks, updateTasks } from "@/api/equipment-service/tasks"
import useTasksStore from "@/store/modules/equipmenttasks.js";
import useUserStore from "@/store/modules/user.js";
const userStore = useUserStore()
// 计算实际耗时（小时）
function calculateDuration(startTime, endTime) {
  if (!startTime || !endTime) return '-';

  const start = new Date(startTime);
  const end = new Date(endTime);

  // 计算时间差（毫秒）
  const diff = end - start;

  // 转换为小时，保留2位小数
  const hours = (diff / (1000 * 60 * 60)).toFixed(2);

  return hours;
}


const { proxy } = getCurrentInstance()

const tasksList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    equipmentId: null,
    taskType: null,
    problemDescription: null,
    solutionDescription: null,
    taskStatus: null,
    priority: null,
    reportedBy: null,
    reportedTime: null,
    assignedToUserId: null,
    actualStartTime: null,
    actualEndTime: null,
    actualDurationHours: null,
    notes: null,
    createdAt: null,
    updatedAt: null
  },
  rules: {
    equipmentId: [
      { required: true, message: "关联的设备ID不能为空", trigger: "blur" }
    ],
    taskType: [
      { required: true, message: "任务类型不能为空", trigger: "change" }
    ],
    reportedTime: [
      { required: true, message: "问题上报时间不能为空", trigger: "blur" }
    ],
    // createdAt: [
    //   { required: true, message: "任务创建时间不能为空", trigger: "blur" }
    // ],
    updatedAt: [
      { required: true, message: "最后更新时间不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

const tasksStore = useTasksStore()
/** 查询设备维护任务跟踪（记录维护工单全生命周期）列表 */
function getList() {
  loading.value = true
  listTasks(queryParams.value).then(response => {
    tasksList.value = response.rows
    tasksStore.setTasksList(response.rows)
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    taskId: null,
    equipmentId: null,
    taskType: null,
    problemDescription: null,
    solutionDescription: null,
    taskStatus: null,
    priority: null,
    reportedBy: null,
    reportedTime: null,
    assignedToUserId: null,
    actualStartTime: null,
    actualEndTime: null,
    actualDurationHours: null,
    notes: null,
    createdAt: null,
    updatedAt: null
  }
  proxy.resetForm("tasksRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.taskId)
  single.value = selection.length != 1
  multiple.value = !selection.length
  if (selection.length === 1) {
    tasksStore.setSelectedTask(selection[0])
  }
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加设备维护任务跟踪（记录维护工单全生命周期）"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _taskId = row.taskId || ids.value
  getTasks(_taskId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改设备维护任务跟踪（记录维护工单全生命周期）"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["tasksRef"].validate(valid => {
    if (valid) {
      if (form.value.taskId != null) {
        updateTasks(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addTasks(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _taskIds = row.taskId || ids.value
  proxy.$modal.confirm('是否确认删除设备维护任务跟踪（记录维护工单全生命周期）编号为"' + _taskIds + '"的数据项？').then(function() {
    return delTasks(_taskIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('equipment-service/tasks/export', {
    ...queryParams.value
  }, `tasks_${new Date().getTime()}.xlsx`)
}

/** 完成任务操作 */
function handleComplete(row) {
  proxy.$modal.confirm('确认将任务"' + row.taskId + '"标记为已完成?').then(function() {
    const currentTime = new Date().toISOString().split('T')[0]; // 获取当前日期
    const completeData = {
      ...row,
      taskStatus: "已完成",
      assignedToUserId: userStore.name, // 设置为当前登录用户
      actualEndTime: currentTime, // 设置为当前时间
      updatedAt: currentTime // 同时更新最后更新时间
    }
    return updateTasks(completeData)
  }).then(() => {
    proxy.$modal.msgSuccess("操作成功")
    getList()
  }).catch(() => {})
}
// 为已完成任务添加行样式
function tableRowClassName({row}) {
  if (row.taskStatus === '已完成') {
    return 'completed-row'
  }
  return ''
}
getList()
</script>
<style>
.el-table .completed-row {
  background-color: #f0f9ff;
}
</style>